const config=require('./config/config');
const Koa=require('koa2');
const {Message}=require('./models/index');
const app=new Koa();

app.keys=config.keys;

//Middlewares
app.use(require('koa-static')('./public'));
app.use(require('./middlewares/responseTime')());
app.use(require('./middlewares/logger')());
app.use(require('koa-session')(config.session,app));
app.use(require('koa-flash')({key:'flash'}));
app.use(require('koa-handlebars-next')({
    cache:app.env!=='development',
    defaultLayout: "main",
    layoutsDir:'views/layouts',
    partialsDir:'views/partials',
    helpers:{
        section(name, opts){
            if(!this._sections)this._sections={};
            this._sections[name]=opts.fn(this);
            return null;
        }
    }
}));

//Internal Server Error
app.use(async (ctx,next)=>{
    try{
        await next();
    }catch(err){
        console.log('\n\nAPP ERROR:');
        console.log(ctx.method+' '+ctx.url);
        console.log('ERROR:\n',err);
        if(/\/api\//.test(ctx.url)){
            ctx.body={
                code:500,
                msg:'Internal Server Error.'
            };
        }else{
            ctx.flash={error:'Internal Server Error.'};
            ctx.redirect('back');
        }
    }
});

//User message
app.use(async (ctx,next)=>{
    let {loginUser}=ctx.session;
    if(loginUser){
        ctx.state.messages=await Message.find({to:loginUser._id,read:false});
    }
    await next();
});
require('./routes/index')(app);

//404 router
app.use(async ctx=>{
    ctx.status=404;
    await ctx.render('404',{
        loginUser:ctx.session.loginUser
    });
});


app.listen(config.port,'0.0.0.0',()=>{
    console.log(`\n\n[${config.name}] port:${config.port} Time:${new Date().toLocaleTimeString()}`);
});